import ansible_runner
import re
import os
import subprocess  # 用于更可靠的本地执行
from datetime import datetime  # 用于超时判断

def execute_solution_code(fault_name, shell_code, inventory="localhost", timeout=300):
    """执行Shell脚本（优化本地执行可靠性，增加超时控制）"""
    hosts = inventory.split(",")
    
    # 本地执行逻辑优化
    if "localhost" in hosts and len(hosts) == 1:
        temp_script = None
        try:
            # 生成唯一临时脚本名
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            temp_script = f"/tmp/{fault_name.replace(' ', '_')}_{timestamp}_fix.sh"
            
            # 写入并设置权限
            with open(temp_script, "w", encoding="utf-8") as f:
                f.write("#!/bin/bash\n")
                f.write(shell_code)
            os.chmod(temp_script, 0o755)
            
            print(f"在本地执行脚本：{temp_script}（超时时间：{timeout}秒）")
            
            # 使用subprocess替代os.popen，支持超时和退出码判断
            result = subprocess.run(
                [temp_script],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,  # 合并标准错误到标准输出
                text=True,
                timeout=timeout  # 关键：设置超时时间
            )
            output = result.stdout
            
            # 优先通过退出码判断结果
            if result.returncode != 0:
                return f"❌ 解决方案1执行失败（退出码：{result.returncode}）：{output[:500]}"
            else:
                return f"✅ 解决方案1执行成功（本地执行）：{output[:500]}"
                
        except subprocess.TimeoutExpired:
            return f"❌ 解决方案1执行超时（超过{timeout}秒未完成）"
        except Exception as e:
            return f"❌ 本地执行出错：{str(e)}"
        finally:
            # 确保临时文件无论成功失败都被删除
            if temp_script and os.path.exists(temp_script):
                try:
                    os.remove(temp_script)
                except:
                    print(f"警告：临时文件 {temp_script} 清理失败")
    
    # 远程执行优化（增加超时）
    playbook = [
        {
            "name": f"Execute solution for {fault_name}",
            "hosts": hosts,
            "gather_facts": False,
            "tasks": [
                {
                    "name": "Run solution shell script",
                    "shell": shell_code,
                    "args": {
                        "executable": "/bin/bash",
                        "timeout": timeout  # Ansible任务级超时
                    },
                    "register": "result"
                },
                {
                    "name": "Output execution result",
                    "debug": {"var": "result.stdout_lines"}
                }
            ]
        }
    ]
    
    try:
        print(f"在远程主机 {inventory} 执行脚本（超时时间：{timeout}秒）")
        runner = ansible_runner.run(
            playbook=playbook,
            inventory={"all": {"hosts": {h: {} for h in hosts}}},
            quiet=False,
            timeout=timeout  # 整体运行超时
        )
        if runner.status == "successful":
            return f"✅ 解决方案1执行成功（目标主机：{inventory}）"
        else:
            # 提取更详细的错误信息
            failures = runner.stats.get('failures', {})
            return f"❌ 解决方案1执行失败：{failures}（状态：{runner.status}）"
    except Exception as e:
        return f"❌ 远程执行过程出错：{str(e)}"

def extract_solution1_code(analysis_content):
    """保持不变，优化正则匹配"""
    pattern = r"\[方案1代码]\s*(.*?)\s*(?=\[解决方案2]|$)"
    match = re.search(pattern, analysis_content, re.DOTALL)
    if match:
        # 清理可能的空行和注释标记
        code = match.group(1).strip()
        return re.sub(r'^\s*#.*?$', '', code, flags=re.MULTILINE).strip()
    return None